<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-07-08
 * Time: 11:11
 */

namespace app\api\service\message;


use app\api\service\Token;
use think\Exception;
use think\facade\Cache;

class MessageSer extends Token
{
    private $wxAppId;
    private $wxAppSecret;
    private $wxAccessUrl;

    function __construct()
    {
        $this->wxAppId = config('wechat.app_id');
        $this->wxAppSecret = config('wechat.app_secret');
        $this->wxAccessUrl = sprintf(config('wechat.token_url'),
            $this->wxAppId,$this->wxAppSecret);
    }

    // 下单给取送员发送模板消息
    public function index_one($openid,$first,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5,$remark,$url)
    {
        $accessToken = $this->getAccessToken();
        $api = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;
        $json = $this->indexOne($openid,$first,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5,$remark,$url);
        $output = https_post($api,$json);
        $out_arr = json_decode($output,true);
        if($out_arr['errcode'] != 0){
            $accessToken = $this->getToken();
            $api = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;
            $json = $this->indexOne($openid,$first,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5,$remark,$url);
            $output = https_post($api,$json);
            $out_arr = json_decode($output,true);
            file_put_contents(SITE_PATH.'/message.txt', 'openid:【'  .$openid.'】'.$output, FILE_APPEND);
        } else {
            file_put_contents(SITE_PATH.'/message.txt', 'openid:【'  .$openid.'】'.$output, FILE_APPEND);
        }
    }

    // 下单给取送员发送模板消息
    private function indexOne($openid,$first,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5,$remark,$url)
    {
        $template = array(
            'touser'=>$openid,
            'template_id'=>'45ZOtONSYE-3haxItz9u-whZWbT0AJdOl9F0RTIIMhU',
            'url'=>$url,
            'topcolor'=>'#7b68ee',
            'miniprogram' => array(
                'appid' => config('wx.app_id'),
                'pagepath' => 'pages/user/qusongyuan'
            ),
            'data'=>array(
                'first'=>array('value'=>urlencode($first)),
                'keyword1'=>array('value'=>urlencode($keyword1)),
                'keyword2'=>array('value'=>urlencode($keyword2)),
                'keyword3'=>array('value'=>urlencode($keyword3)),
                'keyword4'=>array('value'=>urlencode($keyword4)),
                'keyword5'=>array('value'=>urlencode($keyword5)),
                'remark'=>array('value'=>urlencode($remark))
            )
        );
        return urldecode(json_encode($template));
    }


    private function getAccessToken()
    {
        $token = Cache::get('wechat_access_token');
        if(!$token)
        {
            $access_token = $this->getToken();
        }
        else{
            $access_token = $token;
        }
        return $access_token;
    }

    /**
     * @param $openid
     * 获取accessToken
     */
    private function getToken()
    {
        $wxResult = curl_get($this->wxAccessUrl);
        if(empty($wxResult))
        {
            throw new Exception('获取access_token时异常,微信内部错误');
        }
        else{
            $loginFail = array_key_exists('errcode',$wxResult);
            if($loginFail)
            {
                throw new Exception($wxResult['errmsg']);
            }
            else{
                $expire_in = config('setting.access_token_expire_in');
                $result = cache('wechat_access_token',$wxResult['access_token'],$expire_in);
                if(!$result)
                {
                    throw new Exception('服务器缓存异常');
                }
                return $wxResult['access_token'];
            }
        }
    }
}